package com.nebula.sirius.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.nebula.sirius.kit.ConsKit;
import com.nebula.sirius.message.SiriusResponse;
import com.nebula.sirius.message.SiriusResult;
import com.nebula.sirius.message.SiriusSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 功能描述: web拦截器<br>
 * 所属包名: com.nebula.sirius.Interceptor<br>
 * 创建人　: 白剑<br>
 * 创建时间: 2018/04/03 12:36:14<br>
 * 当前版本: 1.0<br>
 * 修改历史: <br>
 * 修改时间　　　　　修改人　　　　　版本变更　　　　　修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
public class WebInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();

        System.out.println(String.format("----- web required: [%s] start -----", uri));

        // session过滤，由于路由交给前端控制，所以这里只过滤rest请求，session超时跳转由前端响应
        SiriusSession siriusSession = (SiriusSession) request.getSession().getAttribute(ConsKit.USER_SESSION);
        if (null == siriusSession && !uri.contains(ConsKit.LOGIN_PATH)) {
            PrintWriter out = response.getWriter();
            SiriusResponse siriusResponse = new SiriusResponse();
            siriusResponse.setResult(SiriusResult.sessionexpired);
            out.write(JSONObject.toJSONString(siriusResponse));
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        System.out.println(String.format("----- web required: [%s] end -----", request.getRequestURI()));
        System.out.println();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }
}
